package com.liu.jackjson;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.liu.fastjson.User;
import org.junit.Test;

import javax.swing.text.DateFormatter;
import java.text.DateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author LIU
 * @version 1.0
 * @description TODO
 * @date 2024/4/23 10:47
 */
public class JacksonTest {
    /**
     * 线程安全的，可以作为成员变量
     */
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 全局配置：序列化时只包含非空属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 全局配置：序列化时不包含null和""
//        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        // 反序列化忽略多余字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // 默认序列化配置
//        objectMapper.findAndRegisterModules();

        // 手动全局序列化和反序列化配置
        JavaTimeModule module = new JavaTimeModule();
        module.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        module.addDeserializer(LocalDateTime.class,
                new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        objectMapper.registerModule(module);
    }

    /**
     * 序列化
     */
    @Test
    public void test() throws JsonProcessingException {
        Person user = new Person();
        user.setName("小明");
        user.setId(1L);
        user.setAddr("成都");
        user.setRegisterDate(new Date());
        user.setBirthDay(LocalDateTime.now());
        user.setPROJECT_CODE("");
        String str = objectMapper.writeValueAsString(user);

        System.out.println(str);
    }
    /**
     * 反序列化
     */
    @Test
    public void test2() throws JsonProcessingException {
        String str = "{\"id\":1,\"name\":\"小明\",\"registerDate\":\"2024-04-24 09:52:29\",\"birthDay\":\"2024-04-24 09:52:29\",\"address222\":\"成都\"}";
        Person person = objectMapper.readValue(str, Person.class);

        System.out.println(person);
    }
}
